<script setup lang="ts">
import { watch } from 'vue';

import { useVbenForm } from '#/adapter/form';
import {
  createBusinessCelebrations,
  getBusinessCelebrations,
  updateBusinessCelebrations,
} from '#/api/per/businessCelebrations';

import { useFormSchema } from '../celebrations/data';

const props = defineProps<{ data?: any }>();

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: { class: 'w-full' },
    labelWidth: 80,
  },
  wrapperClass: 'grid-cols-2',
  layout: 'horizontal',
  schema: useFormSchema(),
  showDefaultActions: false,
});

// -----------------------------
// 加载详情
// -----------------------------
watch(
  () => props.data,
  async (val) => {
    if (!val?.id) {
      formApi.resetForm();
      return;
    }
    const detail = await getBusinessCelebrations({ id: val.id });
    formApi.setValues(detail);
  },
  { immediate: true },
);

// -----------------------------
// 保存（新增 / 修改）
// -----------------------------
const onConfirm = async () => {
  const { valid } = await formApi.validate();
  if (!valid) return false;

  const formData = await formApi.getValues();

  try {
    if (formData.id) {
      // 修改
      await updateBusinessCelebrations(formData);
    } else {
      // 新增
      await createBusinessCelebrations(formData);
    }
    return true; // 返回给父组件
  } catch (error) {
    console.error(error);
    return false;
  }
};

// 准备暴露给父组件调用
defineExpose({
  onConfirm,
});
</script>

<template>
  <Form />
</template>
